package com.smartlink.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;
import com.smartlink.pojo.Classroom;
import com.smartlink.pojo.Sensors;
import com.smartlink.pojo.Setting;
import com.smartlink.service.ClassroomService;
import com.smartlink.service.SettingService;
import com.smartlink.util.EmailUtil;
import com.smartlink.util.HttpClientUtil;

public class AppAction extends ActionSupport {
	private String clsroomId;
	private String settingId;
	private ClassroomService classroomService;
	private SettingService settingService;
	private EmailUtil emailUtil;
	private HttpClientUtil httpClient;
	private String cmdValue;
	private static final long serialVersionUID = 1L;
	private Log log = LogFactory.getLog(AppAction.class);

	/**
	 * 根据教师ID获取最新的环境信息
	 * 
	 * @throws Exception
	 */
	public void getEnvData() throws Exception {

		Classroom classroom = classroomService.getByid(clsroomId);
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		String url = "http://api.heclouds.com/devices/" + classroom.getDeviceId()
				+ "/datapoints?datastream_id=waterTemperature,roomTemperature,soilRh,roomRh";
		JSONObject getData = httpClient.doGet(url);
		log.info(getData);
		out.println(getData);
		out.flush();
		out.close();

	}

	/**
	 * 发送报警电子邮件
	 */
	public void sendEmail() {
		try {
			// {"errorCode":"110000","className":"逸夫理工323","camera":"[1099597_1462323024871_camera]","email":"smartlinke@163.com"}
			HttpServletResponse response = ServletActionContext.getResponse();
			PrintWriter out = response.getWriter();
			HttpServletRequest request = ServletActionContext.getRequest();
			String info = request.getParameter("info");
			if (info != null && !"".equals(info.trim())) {
				JSONObject json = new JSONObject(info);
				String email = json.getString("email");
				String classroomName = json.getString("className");
				String errorCode = json.getString("errorCode");
				String cameras = json.getString("camera");
				File[] files = downloadCamera(cameras);
				emailUtil.sendEmail(email, classroomName, errorCode, files);
				log.info(json);
				out.println("success");
			} else {
				out.println("error");
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private File[] downloadCamera(String cameras) {
		JSONArray array = new JSONArray(cameras);
		int length = array.length();
		String rootPath = ServletActionContext.getServletContext().getRealPath("camera");
		OutputStream outputStream = null;
		File[] fils = new File[length];

		for (int i = 0; i < length; i++) {
			String index = array.getString(i);
			String url = "http://api.heclouds.com/bindata/" + index;
			File file = new File(rootPath, i + ".jpg");
			try {
				outputStream = new FileOutputStream(file);
				boolean flag = httpClient.doDownload(url, outputStream);
				if (flag) {
					fils[i] = file;
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return fils;

	}

	/**
	 * 控制灯光 1 开启 0 关闭
	 * 
	 * @throws Exception
	 */
	public void controlLight() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		Classroom classroom = classroomService.getByid(clsroomId);
		Sensors light = getSensors(classroom.getSensorses(), "light");
		String url = "http://" + classroom.getPiIp() + light.getApi() + "?light=" + cmdValue;
		JSONObject info = httpClient.doGet(url);
		PrintWriter out = response.getWriter();
		out.println(info);
		out.close();

	}

	/**
	 * 控制风扇 1 开启 0 关闭
	 * 
	 * @throws Exception
	 */
	public void controlFan() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		Classroom classroom = classroomService.getByid(clsroomId);
		Sensors fan = getSensors(classroom.getSensorses(), "fan");
		String url = "http://" + classroom.getPiIp() + fan.getApi() + "?fan=" + cmdValue;
		JSONObject info = httpClient.doGet(url);
		PrintWriter out = response.getWriter();
		out.println(info);
		out.close();

	}

	/**
	 * 控制窗帘 1 打开 0 关闭
	 * 
	 * @throws IOException
	 * 
	 */
	public void controlCurtain() throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		Classroom classroom = classroomService.getByid(clsroomId);
		Sensors curtain = getSensors(classroom.getSensorses(), "curtain");
		String url = "http://" + classroom.getPiIp() + curtain.getApi() + "?curtain=" + cmdValue;
		JSONObject info = httpClient.doGet(url);
		PrintWriter out = response.getWriter();
		out.println(info);
		out.close();

	}

	/**
	 * 报警APP 访问得到设置表
	 * 
	 * @throws Exception
	 */
	public void getSetting() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		Setting setting = settingService.getSettingById(settingId);
		PrintWriter out = response.getWriter();
		if (setting != null) {
			JSONObject json = new JSONObject();
			json.put("alarmEmail", setting.getAlarmEmail());
			json.put("alarmPhone", setting.getAlarmPhone());
			json.put("alarmBeginDate", setting.getAlarmBeginDate());
			json.put("alarmOverDate", setting.getAlarmOverDate());
			json.put("isAlarm", setting.getIsAlarm());
			json.put("camera", setting.getCamera());
			json.put("errorCode", setting.getErrorCode());
			out.println(json.toString());
		} else {
			out.println("{\"info\":\"no setting\"}");
		}
		out.flush();
		out.close();
	}

	/**
	 * 下载教室信息，用于APP通过蓝牙比对在哪间教室
	 * 
	 * @throws Exception
	 */
	public void downloadClassRoomInfo() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		List<String> classroomInfos = classroomService.getCLassInfoList();
		log.info("classroomInfos" + classroomInfos);
		JSONObject jsonObject = new JSONObject();
		if (classroomInfos.isEmpty()) {
			jsonObject.put("result_code", 1);
			jsonObject.put("result", "empty");
		} else {
			jsonObject.put("result_code", 0);
			jsonObject.put("result", classroomInfos);
		}
		out.println(jsonObject.toString());
		out.close();

	}

	// ***************************************************************************************
	private Sensors getSensors(Set<Sensors> set, String sernsorName) {
		List<Sensors> list = new ArrayList<>(set);
		for (Sensors s : list) {
			if (sernsorName.equals(s.getSensorsName())) {
				return s;
			}
		}
		return null;
	}

	public String getClsroomId() {
		return clsroomId;
	}

	public void setClsroomId(String clsroomId) {
		this.clsroomId = clsroomId;
	}

	public String getCmdValue() {
		return cmdValue;
	}

	public void setCmdValue(String cmdValue) {
		this.cmdValue = cmdValue;
	}

	public ClassroomService getClassroomService() {
		return classroomService;
	}

	public void setClassroomService(ClassroomService classroomService) {
		this.classroomService = classroomService;
	}

	public HttpClientUtil getHttpClient() {
		return httpClient;
	}

	public void setHttpClient(HttpClientUtil httpClient) {
		this.httpClient = httpClient;
	}

	public EmailUtil getEmailUtil() {
		return emailUtil;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	public String getSettingId() {
		return settingId;
	}

	public void setSettingId(String settingId) {
		this.settingId = settingId;
	}

	public SettingService getSettingService() {
		return settingService;
	}

	public void setSettingService(SettingService settingService) {
		this.settingService = settingService;
	}

}
